if not SERVER then return end

UTeam = {}

UTeam.BASETEAMINDEX = 20

UTeam.CONFIG = "UTeam.txt"

if not file.Exists( UTeam.CONFIG ) then
	Msg( "[UTeam Error] UTeam config file missing.\n" )
	return
end
local t = util.KeyValuesToTable( file.Read( UTeam.CONFIG ) )

if not t.teams then
	Msg( "[UTeam Error] UTeam config teams table missing.\n" )
	return
end
UTeam.teams = {}
for k,v in pairs( t.teams ) do
	UTeam.teams[tonumber(k)]=v
end

if not t.gamemodes then
	Msg( "[UTeam Error] UTeam config gamemodes table missing.\n" )
	return
end
UTeam.gamemodes = t.gamemodes

function UTeam.checkGamemode()
	for _,v in pairs( UTeam.gamemodes ) do
		if string.lower(GAMEMODE.Name) == string.lower(v) then return true end
	end
	hook.Remove( "PlayerSpawn", "UTeamSetTeam" )
	hook.Remove( "PlayerInitialSpawn", "UTeamSetupTeams" )
	return false
end

function UTeam.setTeam( ply )
	if not UTeam.checkGamemode() then return end

	for k,v in ipairs( UTeam.teams ) do
		if ply:IsUserGroup( v.group ) then
			ply:SetTeam( UTeam.BASETEAMINDEX + k )
			if v.hp then ply:SetHealth( v.hp ) end
			if v.armor then ply:SetArmor( v.armor ) end
			if v.model then timer.Simple( 0.1, ply.SetModel, ply, player_manager.TranslatePlayerModel( v.model ) )end
			if v.plytable then
				timer.Simple( 0.1, function(ply, v)
					for _,v in pairs(v.plytable) do
						k = string.sub( v, 1, string.find( v, ":" ) - 1 )
						v = string.sub( v, string.find( v, ":" ) + 1 )
						ply:GetTable()[k] = tonumber(v) or v
					end
				end, ply, v)
			end
			break
		end
	end
end
hook.Add( "PlayerSpawn", "UTeamSetTeam", UTeam.setTeam )

function UTeam.setupTeams( ply )
	if not UTeam.checkGamemode() then return end
	
	for k,v in ipairs( UTeam.teams ) do
		team.SetUp( UTeam.BASETEAMINDEX + k, v.name, v.color )
		ply:SendLua( "team.SetUp(" .. UTeam.BASETEAMINDEX + k .. ",\"" .. v.name .. "\",Color(" .. v.color.r .. "," .. v.color.g .. "," .. v.color.b .. "," .. v.color.a .. "))" )
	end
end
hook.Add( "PlayerInitialSpawn", "UTeamSetupTeams", UTeam.setupTeams )